﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Forest.Lion.Data;
using System.Collections.ObjectModel;
using Forest.Lion.Domain.Contracts;

namespace Forest.Lion.Domain.Handlers {
    public class MessageTemplateAppService {
        private readonly IMessageTemplateRepository _messageTemplateRepository;

        public MessageTemplateAppService(IMessageTemplateRepository messageTemplateRepository) {
            this._messageTemplateRepository = messageTemplateRepository;
        }

        public IEnumerable<Model.MessageTemplate> GetMessageTemplatesForCompany(Guid companyId) {
            var messageTemplates = _messageTemplateRepository.GetMessageTemplatesForCompany(companyId)
                 .OrderByDescending(m => m.LastUpdated)
                 .ToArray();

            return new ReadOnlyCollection<Model.MessageTemplate>(messageTemplates);
        }

        public void Create(IMessageTemplateFormModel formModel, Guid companyId) {
            var messageTemplate = new Model.MessageTemplate {
                CompanyId = companyId,
                TemplateContent = formModel.TemplateContent,
                Subject = formModel.Subject,
                LastUpdated = DateTime.Now,
                CreatedBy = companyId,
                DateCreated = DateTime.Now,
                Deleted = false,
                Id = formModel.Id,
                ModifiedBy = companyId
            };

            _messageTemplateRepository.Create(messageTemplate);
        }

        public void Update(IMessageTemplateFormModel formModel, Guid companyId) {
            var messageTemplate = _messageTemplateRepository.GetMessageTemplate(formModel.Id);

            messageTemplate.Subject = formModel.Subject;
            messageTemplate.TemplateContent = formModel.TemplateContent;
            messageTemplate.ModifiedBy = companyId;
            messageTemplate.LastUpdated = DateTime.Now;

            _messageTemplateRepository.Update(messageTemplate);
        }

        public Model.MessageTemplate GetMessageTemplate(Guid templateId) {
            return _messageTemplateRepository.GetMessageTemplate(templateId);
        }
    }
        
}
